<script setup lang="ts">
import { http } from '@/apis';
import { closeToast, showLoadingToast, showToast, type ActionSheetAction } from 'vant';
import { ref } from 'vue';
import base64ToBlob from 'b64-to-blob'

// 5. 获取个人资料
const profile = ref<ProfileInfo>({} as ProfileInfo)
const getProfile = async () => {
  try {
    // 5.1 开启提示
    showLoadingToast({
      message: '正在加载中...',
      duration: 0,
      forbidClick: true
    })
    // 5.2 发请求拿数据
    const res = await http.get<MkResponse<ProfileInfo>>('/member/profile')
    profile.value = res.data.result
    console.log(profile.value);
    // 5.4 取出生日给到页面
    birthday.value = res.data.result.birthday.split('-')
    // 5.5 取出职业给到页面
    profession.value.push(res.data.result.profession)
  } finally {
    // 5.3 关闭提示
    closeToast()
  }
}
getProfile()



// 1. 头像弹层的显示/隐藏
const showAvatarSheet = ref(false)
const selectAvatarSheet = async (action: ActionSheetAction, index: number) => {
  if (index === 0) {
    const data = await mk.pickerPhoto()
    onUpdateAvatar(data)
  } else if (index === 1) {
    const data = await mk.pickerCamera()
    onUpdateAvatar(data)
  }
}


// 1.1 上传头像
const onUpdateAvatar = async (data: string) => {
  if (!data) return showToast('请选择图片')
  try {
    // 1.1.1 把bas464编码转成图片文件
    const image = base64ToBlob(data, 'image/jpeg')
    console.log(image);
    // 1.1.2 把文件放入formData对象
    const fd = new FormData()
    fd.append('file', image, Date.now() + '.jpeg')

    // 1.1.3 调用接口
    showLoadingToast({
      message: '正在上传中...',
      duration: 0,
      forbidClick: true
    })
    const res = await http.post<MkResponse<{ avatar: string }>>('/member/profile/avatar', fd)
    profile.value.avatar = res.data.result.avatar

    // 1.1.4 修改原生侧的头像
    const user = mk.queryUser()
    user.avatar = res.data.result.avatar
    mk.updateUser(user)
    showToast('头像上传成功')
  } catch (e) {
    showToast('头像上传失败')
  } finally {
    closeToast()
  }

}

// 2. 选择生日
const showBirthdayPopup = ref(false)
const onChangeBirthday = () => {
  // 2.1 隐藏弹层
  showBirthdayPopup.value = false
  profile.value.birthday = birthday.value.join('-')
}
// 2.2 定义一个属性去和datePicker双向绑定
const now = new Date()
const birthday = ref([now.getFullYear().toString(), String(now.getMonth() + 1), now.getDate().toString()])




// 3. 获取所在地
const areaColumns = ref<AreaColumns>({} as AreaColumns)
const getAreaColumns = async () => {
  const res = await mk.getAreaColumns()
  areaColumns.value = res
  // console.log(areaColumns.value);
}
getAreaColumns()

const showLocationPopup = ref(false)
const onSelectedLocation = (data: { selectedValues: number[] }) => {
  // 3.1 隐藏弹层
  showLocationPopup.value = false
  // 3.2 根据省市区的编码获取省市区的名称
  const provinceName = areaColumns.value.province_list[data.selectedValues[0]]
  const cityName = areaColumns.value.city_list[data.selectedValues[1]]
  const countyName = areaColumns.value.county_list[data.selectedValues[2]]
  // console.log(`${provinceName}-${cityName}-${countyName}`);
  profile.value.fullLocation = `${provinceName} ${cityName} ${countyName}`

  // 3.3 记录省市区的编码
  profile.value.provinceCode = data.selectedValues[0]
  profile.value.cityCode = data.selectedValues[1]
  profile.value.countyCode = data.selectedValues[2]
}

// 4. 选择职业
const professionList = [
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' }
]
const showProfessionPopup = ref(false)
const onChangeProfession = (data: { selectedValues: string[] }) => {
  // console.log(data.selectedValues);
  showProfessionPopup.value = false
  // console.log(profession.value);
  profile.value.profession = data.selectedValues[0]
}
const profession = ref<string[]>([])


// 6. 保存资料
const isLoading = ref(false)
const onSave = async () => {
  console.log(profile.value);

  // 6.1 非空处理
  if (!profile.value.nickname) {
    return showToast('昵称不能为空')
  }

  // 6.2 调用接口
  try {
    isLoading.value = true
    mk.vibrator()
    await http.put('/member/profile', profile.value)

    // 6.3 修改原生侧的数据
    const user = mk.queryUser()
    user.nickname = profile.value.nickname
    mk.updateUser(user)
    showToast('保存资料成功')

  } catch (error) {
    showToast('保存资料失败')
  } finally {
    isLoading.value = false
  }
}

</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image round width="100" height="100" :src="profile.avatar" class="avatar-img"></van-image>
      <div class="avatar-btn" @click="showAvatarSheet = true">
        <span>修改头像</span>
      </div>
    </div>
    <!-- 选择头像动作弹层 -->
    <van-action-sheet v-model:show="showAvatarSheet" :actions="[{ name: '相册' }, { name: '拍照' }]" cancel-text="取消"
      close-on-click-action @select="selectAvatarSheet" />

    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field v-model="profile.account" label="账号" readonly />
      <van-field v-model="profile.nickname" label="昵称" placeholder="请输入昵称" />
      <van-cell title="性别" class="gender">
        <van-radio-group v-model="profile.gender">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field v-model="profile.birthday" label="生日" placeholder="请选择日期" readonly @click="showBirthdayPopup = true" />

      <!-- 选择生日弹层 -->
      <van-popup v-model:show="showBirthdayPopup" position="bottom">
        <van-date-picker v-model="birthday" title="选择日期" :min-date="new Date('1980-01-01')" :max-date="new Date()"
          @cancel="showBirthdayPopup = false" @confirm="onChangeBirthday" />
      </van-popup>

      <van-field v-model="profile.fullLocation" label="所在地" placeholder="请选择所在地" readonly
        @click="showLocationPopup = true" />

      <!-- 选择所在地弹层 -->
      <van-popup v-model:show="showLocationPopup" position="bottom">
        <van-area title="选择所在地" :area-list="areaColumns" @cancel="showLocationPopup = false"
          @confirm="onSelectedLocation" />
      </van-popup>

      <van-field v-model="profile.profession" label="职业" placeholder="请选择职业" readonly
        @click="showProfessionPopup = true" />
      <!-- 选择所在地弹层 -->
      <van-popup v-model:show="showProfessionPopup" position="bottom">
        <van-picker v-model="profession" title="选择职业" :columns="professionList" @confirm="onChangeProfession"
          @cancel="showProfessionPopup = false" />
      </van-popup>
    </van-cell-group>
    <div class="submit">
      <van-button :loading="isLoading" loading-text="正在提交..." round block type="primary"
        @click="onSave">保存资料</van-button>
    </div>
  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

/* 
  默认情况下, 无法修改组件内容的样式
  如果要改, 请深度穿透
  ::v-deep()
*/
.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>